SpringBoot小例子

Author Avatar
子语 2017 - 09 - 23
  • 在其它设备中阅读本文章

第一个Spring Boot应用

创建项目

1.打开 IDEA, 选择 Create New Project
2.左侧菜单选择Spring Initializr, Next即可
3.Project Metadata默认即可,Next
4.Dependencies选择Web中的Web即可,Next
5.Project Name默认即可,finsh

项目结构

demo   // 项目名
|- .idea
|- .mvn
|- src  // 代码存放区
   |- main 
      |- java
         |- com.example.demo // java包
            |- DemoApplication.java  // 项目启动类
      |- resources
         |- static     // 用于存放css,js等样式文件
         |- templates  // 用于存放html文件
         application.properties  // 项目配置文件
   |- test //测试代码存放区
|- target
.gitignore
mvnw
mvnw.cmd
demo.iml
pom.xml // 项目对象模型,添加项目依赖等配置

DemoApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(PersonApplication.class, args);
	}
}

@SpringBootApplication标注它是一个SpringBoot应用,main方法使说明它是主程序,在应用启动时首先被执行。
右键run,然后在浏览器中输入localhost:8080即可访问页面,因为当前未定义页面,因此显示Error Page

第一个页面

com.example.demo文件下创建HelloController.java

package com.example.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController 
public class HelloController {
	// 设置请求路径为 /hello,请求方式为get
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say() {
        return "Hello World!";
    }
}

RestController注解该类是一个控制器。当用户访问指定路径时,将调用say()返回"Hello World"。
右键run,然后在浏览器中输入localhost:8080/hello即可访问页面,此时可在页面看到Hello World!

项目属性配置

建议将项目中application.properties改为application.yml,便于配置

server:
  port: 8080           # 端口号
  context-path: /demo  # 主路径配置
age: 18                # 自定义属性
content: "age: ${age}" # 配置文件中调用属性

获取配置文件中的属性值

package com.example.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController 
public class HelloController {
    @Value("${content}")
	private String content;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say() {
        return content;
    }
}

右键run,然后在浏览器中输入localhost:8080/demo/hello即可访问页面,此时可在页面看到age: 18

当有一系列属性值时

可将其定义为某个属性的子属性

server:
  port: 8080
person:
  name: Tom
  age: 40

定义一个PersonProperties类

package com.temp.person;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component // 将类实例化到Spring容器中
@ConfigurationProperties(prefix = "person")  // 获取前缀为person的配置
public class PersonProperties {
    private String name;
    private Integer age;
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

}

获取配置文件中的值:

package com.example.demo;

import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController 
public class HelloController {
    @Autowired
    private PersonProperties personProperties;  // 定义对象,从而间接获取属性值

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say() {
        return personProperties.getName;
    }
}

右键run,然后在浏览器中输入localhost:8080/demo/hello即可访问页面,此时可在页面看到Tom对于配置文件中属性的读取建议采用该方式

多种配置文件

假设现在有两种配置文件application-dev.yml和application-prod.yml

[application-dev.yml]
demo:
  name: you 
  age: 20

[application-prod.yml]
demo:
  name: you 
  age: 20

只需在application.yml中

spring:
  profiles:
  # 选择要调用的配置文件
    active: dev

当要使用某种时,active设为那个文件的值即可。

Controller的基本使用

注解 功能
@Controller 处理http请求
@RestController Spring4之后新加的注解,原先返回json需要@ResponseBody配合@Controller
@RequestMapping 配置url映射
@PathVariable 获取url中的数据
@RequestParam 获取请求参数的值
@GetMapping 组合注解

访问路径和访问方式

1.@RequestMapping(value = "/hello", method = RequestMethod.GET)设置访问路径为"hello",请求方式为get,可以简写为@GetMapping(value = "/hello")
2.可将路径设为集合,使得访问的路径不同,但请求的资源相同:@RequestMapping(value = {"hello", "hi"})
3.可以为整个类设置访问路径,如下:

package com.example.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController 
@GetMapping(value = "/demo")
public class HelloController {
    @GetMapping(value = {"/hello", "hi"})
    public String say() {
        return "Hello World!";
    }
}

在浏览器输入地址http://localhost:8080/demo/hellohttp://localhost:8080/demo/hi均能看到页面显示Hello World!.

获取路径参数

1.@PathVariable 获取路径参数

@GetMapping(value = "/hello/{id}")
public Integer say(@PathVariable("id") Integer id) {
   return id;
}

在浏览器输入地址http://localhost:8080/hello/100此时页面显示100
2.@RequestParam 获取请求参数

@GetMapping(value = "/hello")
// 获取路径中参数id的值,id可不存在,默认为0
public Integer say(@RequestParam(value = "id",required = false,defaultValue ="0") Integer id) {
    return id;
}

在浏览器输入地址http://localhost:8080/hello/100?id=100此时页面显示100

数据库操作

Java客户端使用Spring-Data-Jpa组件。
JPA(Java Persistence API)定义了一系列对象持久化的标准,目前实现这一规范的产品有Hibernate、TopLink等。

RESTful API设计

请求类型 请求路径 功能
Get /person 获取数据列表
POST /person 添加数据
Get /person/id 根据id获取数据
PUT /person/id 根据id修改数据
DELETE /person/id 根据id删除数据

添加依赖

pom.xml添加jpa依赖和MySQL组件

	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<scope>runtime</scope>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>

修改配置文件

application.yml中添加数据库配置

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver  # 驱动
    url: jdbc:mysql://127.0.0.1:3306/dbperson # 数据库url
    username: root
    password:
  jpa:
    hibernate:
      ddl-auto: udate
    show-sql: true

创建数据表

在Spring Boot中可通过创建实体类,自动生成数据表

package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity  // 注册实体,Spring Boot会自动将其变为数据表
public class Person {
    @Id  // 设为数据表中id属性
    @GeneratedValue   // 设置为自增
    private Integer id;  
    private String name;
    private Integer age;

    public Person() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Spring Boot会将上述代码中类的属性变为数据表的字段。

创建PersonRepository接口

该接口继承JpaRepositoy,实现sql语句

package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface PersonRepository extends JpaRepository<Person, Integer> {

	// 自定义方法,实现通过年龄找数据
    List<Person> findByAge(Integer age);
}

创建PersonController,实现访问时根据访问方式和路径实现数据操作

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import java.util.List;

@RestController
public class PersonController {
    @Autowired
    private PersonRepository personRepository;

    /**
     * 通过get方式访问localhost:8080/person可获取全部数据
     * @return 数据类集
     */
    @GetMapping(value = "/person")
    public List<Person> personList(){
        return personRepository.findAll();
    }

    /**
     * 通过post方式访问localhost:8080/person?name=Jane&age=10可添加数据
     * @param name 数据表的name字段
     * @param age  数据表的age字段
     * @return 返回Person对象
     */
    @PostMapping(value = "/person")
    public Person addPerson(@RequestParam("name") String name,
                            @RequestParam("age") Integer age) {
        Person person = new Person();
        person.setName(name);
        person.setAge(age);
        return  personRepository.save(person);
    }

    /**
     * 通过get方式访问localhost:8080/person/1可获取id为1的数据
     * @param id 要查询的数据id
     * @return Person对象
     */
    @GetMapping(value = "/person/{id}")
    public Person findPersonById(@PathVariable("id") Integer id) {
        return personRepository.findOne(id);
    }

    /**
     * 通过put方式访问localhost:8080/person/1?name=Jane&age=10可将id为1的数据修改
     * @param id 要修改的数据id
     * @return Person对象
     */
    @PutMapping(value = "/person/{id}")
    public Person updatePersonByid(@PathVariable("id") Integer id,
                                   @RequestParam("name") String name,
                                   @RequestParam("age") Integer age) {
        Person person = personRepository.findOne(id);
        person.setName(name);
        person.setAge(age);
        return  personRepository.save(person);
    }

    /**
     * 通过delete方式访问localhost:8080/person/1可将id为1的数据删除
     * @param id 要删除数据的id
     */
    @DeleteMapping(value = "/person/{id}")
    public void deletePersonById(@PathVariable("id") Integer id) {
        personRepository.delete(id);
    }

    /**
     * 通过get方式访问localhost:8080/person/age/10可查找age为10的数据
     * @param age 要查找的年龄
     */
    @GetMapping(value = "/person/age/{age}")
    public List<Person> personListByAge(@PathVariable("age") Integer age) {
        return personRepository.findByAge(age);
    }

    /**
     * 实现事务管理,批量增加数据,一个数据失败,全部数据不得入库
     * @Transactional 用于标注事务管理
     */
    @PostMapping(value = "/person/two")
    @Transactional
    public void addTwoPerson() {
        Person personA = new Person();
        personA.setName("Tony");
        personA.setAge(13);
        personRepository.save(personA);

        Person personB = new Person();
        personB.setName("Maria");
        personB.setAge(18);
        personRepository.save(personB);
    }
}

This blog is under a CC BY-NC-SA 3.0 Unported License
本文链接:http://yov.oschina.io/article/框架/Spring Boot/SpringBoot小例子/